package org.yinxue.swing.core.util;

import java.io.*;
import java.util.Properties;

/**
 * 属性文件操作类 <br>
 *
 * @author zengjian
 * @create 2018-03-14 11:54
 * @since 1.0.0
 */
public final class PropFile {


    private String path;
    private String absolutePath;
    private Properties properties = new Properties();
    private long lastModified;

    public PropFile(String parent, String filePath) {
        this.path = filePath;
        this.absolutePath = parent + "\\" + path;

        File parentFile = new File(parent);
        if (!parentFile.exists()){
            parentFile.mkdirs();
            LogUtil.info(this, parentFile.getPath() + " 文件夹创建成功");
        }
        File file = new File(absolutePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
                LogUtil.info(this, file.getPath() + " 文件创建成功");
            } catch (IOException e) {
                LogUtil.info(this, file.getPath() + " 文件创建失败");
            }
        }
        this.lastModified = new File(absolutePath).lastModified();
        loadProperites();
    }

    private void loadProperites() {
        InputStream is = null;
        try {
            is = new FileInputStream(absolutePath);
            if (is != null) {
                properties.load(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 如果d盘没有,发生读取错误，那就采用用户路径进行读取
            String useDir = System.getProperty("user.dir");
            this.absolutePath = useDir + "\\" + path;
        } finally {
            CloseUtil.close(is);
        }
    }

    public synchronized String getProperty(String key) {
        // 如果文件修改时间发生变化，重新读取
        if (this.lastModified != new File(absolutePath).lastModified()) {
            loadProperites();
        }
        return properties.getProperty(key);
    }

    public synchronized void setProperty(String key, String value) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(absolutePath);
            properties.setProperty(key, value);
            properties.store(fos, null);
            LogUtil.info(this, "[" + key + ":" + value + "]" + " 已存储于文件:" + absolutePath);
        } catch (Exception e) {
            LogUtil.error(this, "更新字段"+"[" + key + ":" + value + "]"+"失败", e);
        } finally {
            CloseUtil.close(fos);
        }
    }
}
